package handlers

import (
	"ai/internal/aiserver/request"
	"ai/internal/db/dao"
	"ai/internal/response"
	"ai/internal/service"
	"net/http"
	"strconv"

	"github.com/gin-gonic/gin"
)

var questionDAO *dao.QuestionDAO
var questionService *service.QuestionService

func SetQuestionDAO(dao *dao.QuestionDAO) {
	questionDAO = dao
}

func SetQuestionService(svc *service.QuestionService) {
	questionService = svc
}

// AddQuestionHandler godoc
// @Summary Add a new question
// @Description Add a new question to the database
// @Tags questions
// @Accept json
// @Produce json
// @Param question body request.ReqAddQuestion true "Question"
// @Success 200 {object} map[string]interface{}
// @Failure 400 {object} map[string]interface{}
// @Router /teacher/questions [post]
func AddQuestionHandler(c *gin.Context, services *service.ServiceManager) {
	req := request.ReqAddQuestion{}
	if err := c.ShouldBindJSON(&req); err != nil {
		response.Error(c, http.StatusBadRequest, err.Error())
		return
	}

	err := services.QuestionService.AddQuestion(req.QuestionText, req.QuestionType, req.Answers)
	if err != nil {
		response.Error(c, http.StatusInternalServerError, err.Error())
		return
	}

	response.Success(c, gin.H{"message": "Question added"})
}

// GetQuestionsHandler godoc
// @Summary Get all questions
// @Description Retrieve all questions from the database
// @Tags questions
// @Produce json
// @Success 200 {object} map[string]interface{}
// @Router /student/questions [get]
func GetQuestionsHandler(c *gin.Context, services *service.ServiceManager) {
	questions, err := services.QuestionService.GetQuestions()
	if err != nil {
		response.Error(c, http.StatusInternalServerError, err.Error())
		return
	}
	response.Success(c, gin.H{"questions": questions})
}

// GetQuestionByID godoc
// @Summary Get a question by ID
// @Description Retrieve a question by its ID
// @Tags questions
// @Produce json
// @Param id path int true "Question ID"
// @Success 200 {object} map[string]interface{}
// @Router /student/questions/{id} [get]
func GetQuestionByID(c *gin.Context) {
	idParam := c.Param("id")
	questionID, err := strconv.ParseUint(idParam, 10, 32)
	if err != nil {
		response.Error(c, http.StatusBadRequest, "Invalid question ID")
		return
	}

	question, err := questionDAO.GetQuestionByID(uint(questionID))
	if err != nil {
		response.Error(c, http.StatusInternalServerError, err.Error())
		return
	}
	response.Success(c, gin.H{"question": question})
}
